package cn.frh.filter;

import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.SneakyThrows;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;

@Component
public class LoginFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        // 1.获取请求地址
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        String uri = request.getRequestURI();
        // 2.判断请求地址里是否有login和register
        if (uri.endsWith("login")||uri.endsWith("register")){
            return false;
        }
        return true;
    }

    @SneakyThrows
    @Override
    public Object run() throws ZuulException {
        // 1.获取请求中的token
        RequestContext requestContext = RequestContext.getCurrentContext();
        String token = requestContext.getRequest().getHeader("token");
        HttpServletResponse response = RequestContext.getCurrentContext().getResponse();
        response.setContentType("application/json;charset=utf-8");
        // 2.判断请求中token是否存在
        if (StringUtils.isEmpty(token)){
            // 如果用户没有登录 就响应success/msg/obj
            PrintWriter writer = response.getWriter();
            HashMap<String, Object> map = new HashMap<>();
            map.put("success:",false);
            map.put("msg:","请先登录");
            map.put("obj:","noLogin");
            String strMap = JSONObject.toJSONString(map);
            writer.write(strMap);
            // 3.阻止过滤器的后续执行方案
            RequestContext.getCurrentContext().setSendZuulResponse(false);
        }
        //不管返回什么 都会忽略 因为上一步已经阻止后续方案了
        return null;
    }
}
